package com.songlanyun.modules.account.service.impl;

import java.util.Map;

import javax.annotation.Resource;

import com.songlanyun.pay.bean.AdaMemberBean;
import com.songlanyun.pay.common.util.apakjp.AdaKjPayManager;
import com.songlanyun.pay.service.AdaKjPayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.account.dao.UserVerifiedDao;
import com.songlanyun.modules.account.entity.UserVerifiedEntity;
import com.songlanyun.modules.account.model.dto.UserVerifiedDTO;
import com.songlanyun.modules.account.service.CommonService;
import com.songlanyun.modules.account.service.UserVerifiedService;
import com.songlanyun.modules.user.exception.UserException;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

/**
 * 实名认证
 *
 * @author lijiahe
 * @date 2022-09-22
 */
@Service("userVerifiedService")
public class UserVerifiedServiceImpl extends ServiceImpl<UserVerifiedDao, UserVerifiedEntity> implements UserVerifiedService {

    @Resource
    private CommonService commonService;

    @Resource
    private AdaKjPayService adaKjPayService;


    @Value("${spring.profiles.active}")
    private String profilesActive;


    @Value("${realnamecheck.key}")
    private String realNameAuthenticationKey;

    /**
     * 实名认证KEY
     */
    //private final static String REAL_NAME_AUTHENTICATION_KEY = "011726cbb69e31e60d4fd2bd156dffa7";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String realName = MapUtil.getStr(params, "realName");
        String identityNumber = MapUtil.getStr(params, "identityNumber");
        IPage<UserVerifiedEntity> page = this.page(new Query<UserVerifiedEntity>().getPage(params),
            new LambdaQueryWrapper<UserVerifiedEntity>()
                .like(StrUtil.isNotBlank(realName), UserVerifiedEntity::getRealName, realName)
                .like(StrUtil.isNotBlank(identityNumber), UserVerifiedEntity::getIdentityNumber, identityNumber)
                .orderByDesc(UserVerifiedEntity::getCreateTime));
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void realNameAuth(UserVerifiedDTO dto)  {
        String realName = dto.getRealName();
        String identityNumber = dto.getIdentityNumber();
        // 检查用户实名是否已存在
        loadByIdentityNumber(identityNumber, true);
        // 判断是否是强制实名
//        if (!dto.isHard()) {
            // 检查验证码是否正确
            commonService.checkVerCode(dto.getMobile(), dto.getCaptcha());
//        }
        if (this.verificationNameAndIdCard(realName, identityNumber)) {
            UserVerifiedEntity entity = new UserVerifiedEntity();
            entity.setId(dto.getId());
            entity.setRealName(realName);
            entity.setIdentityNumber(identityNumber);
            baseMapper.insert(entity);
            AdaMemberBean bean = new AdaMemberBean();
            bean.setUserName(realName);
            bean.setTelNo(dto.getMobile());
            bean.setCertType("00");
            bean.setCertId(identityNumber);
            bean.setMemberId(getKjMemberId(entity.getId()));
            try {
                // 判断是否是强制实名
//                if (!dto.isHard()) {
                    adaKjPayService.createAdaMember(bean,(o)->{
                        entity.setUploadKj(true);
                        this.baseMapper.updateById(entity);
                        return null;
                    });
//                }
//                entity.setUploadKj(true);
//                this.baseMapper.updateById(entity);
            }
            catch (Exception ex)
            {
                if (ex.getMessage().equals("member_id已存在")){
                    baseMapper.updateById(entity);
                }else {
                    throw new RRException(ex.getMessage());
                }
            }
        } else {
            throw new RRException(UserException.USER_VERIFIED);
        }
    }

    @Override
    public String getKjMemberId(Long userId)
    {
        return String.format("%s_%s",this.profilesActive,userId.toString());
    }

    @Override
    public UserVerifiedEntity loadByIdentityNumber(String identityNumber, Boolean tw) {
        UserVerifiedEntity userVerifiedEntity = baseMapper.selectOne(
            new LambdaQueryWrapper<UserVerifiedEntity>().eq(UserVerifiedEntity::getIdentityNumber, identityNumber)
                .orderByDesc(UserVerifiedEntity::getCreateTime).last("limit 1"));
        if (tw) {
            if (ObjectUtil.isNotNull(userVerifiedEntity)) {
                throw new RRException(UserException.USER_EXIST_VERIFIED);
            }
        }
        return userVerifiedEntity;
    }

    @Override
    public UserVerifiedEntity info(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public UserVerifiedEntity loadById(Long id, Boolean tw) {
        UserVerifiedEntity entity = baseMapper.selectById(id);
        if (tw) {
            if (ObjectUtil.isNull(entity)) {
                throw new RRException(UserException.USER_NOT_EXIST_VERIFIED);
            }
        }
        return entity;
    }

    /**
     * 验证姓名和身份证能否对应上
     *
     * @param realName
     * @param identityNumber
     * @return
     */
    public Boolean verificationNameAndIdCard(String realName, String identityNumber) {
        String url = "http://op.juhe.cn/idcard/query?key=" + this.realNameAuthenticationKey + "&idcard=" + identityNumber
            + "&realname=" + realName + "&orderid=" + "1";
        HttpResponse execute =
            HttpRequest.get(url).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").execute();
        JSONObject body = JSONObject.parseObject(execute.body());
        String errorCode = body.getString("error_code");
        if ("0".equals(errorCode)) {
            JSONObject result = body.getJSONObject("result");
            System.err.println(result);
            // 1：匹配 2：不匹配
            String res = result.getString("res");
            return "1".equals(res);
        } else {
            return false;
        }
    }
}
